using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Write.Controllers
{
    /// <summary>
    /// 医院院区管理控制器
    /// 提供院区相关的写操作接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class HospitalAreaController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<HospitalAreaController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public HospitalAreaController(IMediator mediator, ILogger<HospitalAreaController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 创建新的医院院区
        /// </summary>
        /// <param name="createDto">院区创建信息</param>
        /// <returns>创建成功的院区信息</returns>
        [HttpPost]
        [ProducesResponseType(typeof(APIResult<HospitalAreaDto>), 200)]
        [ProducesResponseType(typeof(APIResult<HospitalAreaDto>), 400)]
        public async Task<ActionResult<APIResult<HospitalAreaDto>>> CreateHospitalArea([FromBody] HospitalAreaCreateDto createDto)
        {
            try
            {
                _logger.LogInformation("接收到创建医院院区请求，院区名称：{Name}", createDto.Name);

                // 参数验证
                if (!ModelState.IsValid)
                {
                    var errors = ModelState
                        .SelectMany(x => x.Value?.Errors ?? Enumerable.Empty<Microsoft.AspNetCore.Mvc.ModelBinding.ModelError>())
                        .Select(x => x.ErrorMessage)
                        .ToList();
                    
                    _logger.LogWarning("创建医院院区参数验证失败：{Errors}", string.Join(", ", errors));
                    return BadRequest(new APIResult<HospitalAreaDto>
                    {
                        Code = APIEnum.Fail,
                        Message = string.Join("; ", errors),
                        Data = null
                    });
                }

                // 创建命令
                var command = new CreateHospitalAreaCommand
                {
                    Name = createDto.Name,
                    Address = createDto.Address,
                    Phone = createDto.Phone,
                    Description = createDto.Description,
                    IsSelfServiceEnabled = createDto.IsSelfServiceEnabled,
                    Tags = createDto.Tags,
                    Longitude = createDto.Longitude,
                    Latitude = createDto.Latitude,
                    SortOrder = createDto.SortOrder
                };

                // 执行命令
                var result = await _mediator.Send(command);

                if (result.Code == APIEnum.OK)
                {
                    _logger.LogInformation("成功创建医院院区，院区ID：{Id}", result.Data?.Id);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("创建医院院区失败：{Message}", result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理创建医院院区请求时发生异常");
                return StatusCode(500, new APIResult<HospitalAreaDto>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误，请稍后重试",
                    Data = null
                });
            }
        }
    }
}